package cn.tangwei.user.controller;

import cn.tangwei.basic.exception.BusinessException;
import cn.tangwei.basic.utils.AjaxRusult;
import cn.tangwei.user.domain.User;
import cn.tangwei.user.dto.UserDto;
import cn.tangwei.user.service.IUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")
public class UserContorller {
    @Autowired
    private IUserService userService;

    /**
     * 添加和修改
     * @param user
     * @return
     */
    @PutMapping
    public AjaxRusult addOrUpdate(@RequestBody User user){
        try {
            if(user.getId() == null){
                userService.add(user);
            }else {
                userService.update(user);
            }
            return AjaxRusult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage("操作失败");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxRusult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxRusult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage("操作失败");
        }
    }

    /**
     * 查询一条
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.queryById(id);
    }

    /**
     * 查询全部
     * @return
     */
    @GetMapping
    public List<User> queryAll(){
        return userService.queryAll();
    }

    /**
     * 注册接口
     * @param userDto
     * @return
     */
    @PostMapping("/phone/register")
    public AjaxRusult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxRusult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxRusult.me().setMessage("系统繁忙，稍后再试");
        }
    }

}
